<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>socket test</title>
    <!-- CSS only -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<div>
    <h1 class="text-center" id="socketInfo"></h1>
    <div class="text-center" id="msg"></div>
</div>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
    let ws;
    $(() => {
        const host = location.host;
        ws = new WebSocket(`ws://${host}/message/1`);
        // 1 握手环节验证成功之后 自动触发  onopen
        ws.onopen = function() {
            console.log('握手成功')
            ws.send(JSON.stringify({type: 'connected', token: '1'}))
            $('#socketInfo').text('握手成功');
        }

        // 3 一旦服务端有消息 自动触发  onmessage
        ws.onmessage = function(args) {
            try {
                const {type, data} = JSON.parse(args.data)
                if (type === 'pay_notice') {
                    $('#msg').text(data)
                    const utterThis = new window.SpeechSynthesisUtterance(data);
                    window.speechSynthesis.speak(utterThis);
                }
                console.log(type, data)
            } catch (e) {
                console.log(e)
            }
        }
        // 4 断开链接之后  自动触发  onclose
        ws.onclose = function() {
            ws.close()
        }
    })

    // 2 给服务端发送消息  send
    function sendMsg(data) {
        const typ = typeof data
        if (typ === 'object') {
            data = JSON.stringify(data)
        } else {
            data = JSON.stringify({
                'type': 'auth',
                'data': 'hello'
            })
        }
        ws.send(data)
    }
</script>
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>
